package com.ktjy.ktmall.controller;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ktjy.ktmall.domain.SkuInfo;
import com.ktjy.ktmall.service.ISkuInfoService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ktjy.common.annotation.Log;
import com.ktjy.common.core.controller.BaseController;
import com.ktjy.common.core.domain.AjaxResult;
import com.ktjy.common.enums.BusinessType;


import com.ktjy.common.core.page.TableDataInfo;

/**
 * 商品SKU管理Controller
 *
 * @author ktjy
 * @date 2025-03-19
 */
@RestController
@RequestMapping("/goods/info1")
public class SkuInfoController extends BaseController
{
    @Autowired
    private ISkuInfoService skuInfoService;


    /**
     * 查询SKU编码是否存在
     */
//    @PreAuthorize("@ss.hasPermi('goods:info:list')")
    @GetMapping(value = "/querySku/{stockSku}")
    public AjaxResult getInfoSku(@PathVariable("stockSku") String stockSku)
    {
        QueryWrapper<SkuInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stock_sku",stockSku);
        if (skuInfoService.list(queryWrapper).size() > 0){
            return success(true);
        }
        return success(false);
    }

    /**
     * 查询商品SKU管理列表
     */
//    @PreAuthorize("@ss.hasPermi('goods:info:list')")
    @GetMapping("/list")
    public TableDataInfo list(SkuInfo skuInfo)
    {
        startPage();
        List<SkuInfo> list = skuInfoService.selectSkuInfoList(skuInfo);
        return getDataTable(list);
    }


    /**
     * 查询商品SKU管理列表
     */
//    @PreAuthorize("@ss.hasPermi('goods:info:goodsList')")
    @GetMapping("/goodsList")
    public TableDataInfo goodsList()
    {
        List<SkuInfo> list = skuInfoService.selectGoodsList();
        return getDataTable(list);
    }


    /**
     * 导出商品SKU管理列表
     */
    @PreAuthorize("@ss.hasPermi('goods:info:export')")
    @Log(title = "商品SKU管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SkuInfo skuInfo)
    {
        List<SkuInfo> list = skuInfoService.selectSkuInfoList(skuInfo);

        // 添加序号列
        List<Map<String, Object>> exportList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            SkuInfo skuInfoList = list.get(i);
            Map<String, Object> exportData = new LinkedHashMap<>();
            exportData.put("index", i + 1); // 序号列的值自增，从1开始
            exportData.put("id", skuInfoList.getId());
            exportData.put("goodsName",skuInfoList.getGoodsName());
            exportData.put("stockSku", skuInfoList.getStockSku());
            exportData.put("price", skuInfoList.getPrice());
            exportData.put("oldPrice", skuInfoList.getOldPrice());
            exportData.put("inventory", skuInfoList.getInventory());
            exportData.put("picture", skuInfoList.getPicture());

            String status="正常";
            if ( skuInfoList.getStatus() == 1){
                status="停用";
            }

            exportData.put("status",status);
            exportData.put("remark", skuInfoList.getRemark());

            // 把exportData这个键值对集合添加到上面定义的exportList集合中
            // 注意看上面定义时是（List<Map<String, Object>>）
            exportList.add(exportData);
        }

        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.setOnlyAlias(true); // 设置成只导出有别名的字段
        // 自定义标题别名
        writer.addHeaderAlias("id", "SKU编号");
        writer.addHeaderAlias("goodsName", "商品名称");
        writer.addHeaderAlias("stockSku", "sku编码");
        writer.addHeaderAlias("price", "当前价格");
        writer.addHeaderAlias("oldPrice", "原价");
        writer.addHeaderAlias("inventory", "库存数量");
        writer.addHeaderAlias("picture", "商品图片");
        writer.addHeaderAlias("status", "状态");
        writer.addHeaderAlias("remark", "备注");

        writer.write(exportList, true);

        // 自动调整列宽
        writer.autoSizeColumnAll();

        // 设置最小列宽
        int minColumnWidth = 20; // 可以根据需要调整最小列宽
        int columnCount = writer.getSheet().getRow(0).getLastCellNum();
        for (int i = 0; i < columnCount; i++) {
            int width = writer.getSheet().getColumnWidth(i);
            if (width < minColumnWidth * 256) {
                writer.getSheet().setColumnWidth(i, minColumnWidth * 256);
            }
        }


        try {
            // 设置浏览器响应的格式
            String fileName = URLEncoder.encode("商品SKU管理", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out, true);
            out.close();
            writer.close();
        }catch (Exception e){
            System.out.println(e);
        }
    }

    /**
     * 获取商品SKU管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('goods:info:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(skuInfoService.getSelectId(id));
    }

    /**
     * 新增商品SKU管理
     */
    @PreAuthorize("@ss.hasPermi('goods:info:add')")
    @Log(title = "商品SKU管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SkuInfo skuInfo)
    {
        return toAjax(skuInfoService.save(skuInfo));
    }

    /**
     * 修改商品SKU管理
     */
    @PreAuthorize("@ss.hasPermi('goods:info:edit')")
    @Log(title = "商品SKU管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SkuInfo skuInfo)
    {
        return toAjax(skuInfoService.updateById(skuInfo));
    }

    /**
     * 删除商品SKU管理
     */
    @PreAuthorize("@ss.hasPermi('goods:info')")
    @Log(title = "商品SKU管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Integer> ids)
    {
        return toAjax(skuInfoService.removeByIds(ids));
    }
}